package com.example.personalinfoapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText etUsername;
    private EditText etPassword;
    private CheckBox cbAgreement;
    private Button btnLogin;
    private TextView tvRegister;
    private CheckBox cbShowPassword;
    private ProgressBar progressBar;
    private TextView tvLoading;
    private Handler handler;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate");

        // 绑定布局中的控件
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbAgreement = findViewById(R.id.cb_agreement);
        btnLogin = findViewById(R.id.btn_login);
        tvRegister = findViewById(R.id.tv_register);
        cbShowPassword = findViewById(R.id.cb_show_password);
        progressBar = findViewById(R.id.progress_bar);
        tvLoading = findViewById(R.id.tv_loading);

        handler = new Handler();

        // 1. 用户名输入框交互：焦点变化（边框变亮）+ 文本去空格
        etUsername.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                etUsername.setBackgroundResource(R.drawable.edittext_focused);
            } else {
                etUsername.setBackgroundResource(R.drawable.edittext_bg);
            }
        });
        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                String trimText = s.toString().trim();
                if (!trimText.equals(s.toString())) {
                    etUsername.setText(trimText);
                    etUsername.setSelection(trimText.length());
                }
            }
        });

        // 2. 密码输入框交互：焦点变化（边框变亮）+ 显示/隐藏密码
        etPassword.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                etPassword.setBackgroundResource(R.drawable.edittext_focused);
            } else {
                etPassword.setBackgroundResource(R.drawable.edittext_bg);
            }
        });
        cbShowPassword.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 显示密码：普通文本类型
                etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                // 隐藏密码：密码类型
                etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
            // 保持光标在文本末尾
            etPassword.setSelection(etPassword.getText().length());
        });

        // 3. 协议勾选框：控制登录按钮启用/禁用及样式
        cbAgreement.setOnCheckedChangeListener((buttonView, isChecked) -> {
            btnLogin.setEnabled(isChecked);
            btnLogin.setBackgroundTintList(getResources().getColorStateList(
                    isChecked ? R.color.button_enabled : R.color.button_disabled
            ));
        });

        // 4. 登录按钮：点击校验并显示加载进度条
        btnLogin.setOnClickListener(v -> {
            String username = etUsername.getText().toString().trim();
            String password = etPassword.getText().toString().trim();

            if (username.isEmpty()) {
                Toast.makeText(MainActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
            } else if (password.isEmpty()) {
                Toast.makeText(MainActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
            } else if (!cbAgreement.isChecked()) {
                Toast.makeText(MainActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
            } else {
                // 显示加载进度条和提示文字
                progressBar.setVisibility(View.VISIBLE);
                tvLoading.setVisibility(View.VISIBLE);
                btnLogin.setEnabled(false);

                // 模拟3秒加载过程
                handler.postDelayed(() -> {
                    // 隐藏加载进度条和提示文字
                    progressBar.setVisibility(View.GONE);
                    tvLoading.setVisibility(View.GONE);
                    btnLogin.setEnabled(true);

                    // 显示登录成功提示
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                    // 跳转到HomeActivity并传递用户名
                    Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                    intent.putExtra("username", username);
                    startActivity(intent);
                    finish(); // 关闭登录页面
                }, 3000);
            }
        });

        // 5. 注册提示：点击模拟跳转并显示加载
        tvRegister.setOnClickListener(v -> {
            // 显示加载进度条和提示文字
            progressBar.setVisibility(View.VISIBLE);
            tvLoading.setText("正在跳转注册...");
            tvLoading.setVisibility(View.VISIBLE);

            // 模拟3秒加载过程
            handler.postDelayed(() -> {
                // 隐藏加载进度条和提示文字
                progressBar.setVisibility(View.GONE);
                tvLoading.setVisibility(View.GONE);

                Toast.makeText(MainActivity.this, "跳转到注册页", Toast.LENGTH_SHORT).show();
            }, 3000);
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        // 移除所有回调，防止内存泄漏
        handler.removeCallbacksAndMessages(null);
    }
}